<template>
  <div>
    <h1>登录</h1>
    <el-form
      style="max-width: 300px"
      ref="LoginFormRef"
      label-width="auto"
      :model="LoginForm"
      :rules="Loginrules"
      @submit.prevent="submit"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="LoginForm.username"
          name="username"
          id="username"
          autocomplete="username"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="LoginForm.password"
          name="password"
          id="password"
          autocomplete="current-password"
          type="password"
          @keyup.enter="submit"
        />
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="LoginForm.rememberMe">记住密码</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">登录</el-button>
        <el-button type="primary" @click="login1(LoginForm)">登录1</el-button>
      </el-form-item>
    </el-form>
    {{ LoginForm }}
  </div>
</template>

<script setup>
import { useStore } from 'vuex';
import { validateUsername, validatePassword } from "../utils/validate";
import axios from "axios"; 
import axios1 from 'axiosInstance';// 导入封装好的 axios 实例
import { useRouter } from "vue-router";
import { verifyToken } from "../utils/jwtUtils";

const store = useStore();
const LoginFormRef = ref(); //表单引用
let isLoggedIn = localStorage.getItem("token"); //加密后的passworld
let role = ref(); //用户角色
const router = useRouter();

const LoginForm = reactive({
  username: "",
  password: "",
  rememberMe: false,
});

const Loginrules = {
  username: [{ validator: validateUsername, trigger: "blur" }],
  password: [{ validator: validatePassword, trigger: "blur" }],
};

// 页面卸载时，缓存登陆信息
onBeforeUnmount(() => {
  IsRememberMe();
});

//是否记住密码
const IsRememberMe = () => {
  if (LoginForm.rememberMe) {
    localStorage.setItem("rememberMe", LoginForm.rememberMe);
    localStorage.setItem("username", LoginForm.username);
  } else {
    localStorage.removeItem("rememberMe");
    localStorage.removeItem("username");
  }
};

// 页面加载时，自动填充用户名和密码
onMounted(() => {
  LoginForm.rememberMe = localStorage.getItem("rememberMe") === "true";
  if(LoginForm.rememberMe)
  {
    LoginForm.username = localStorage.getItem("username") || "";
    // 解密密码
    if(isLoggedIn!=null)
    {
      // verifyToken(isLoggedIn).then(({password}) => {
      //   console.log(123);
      //   LoginForm.password = password;
      // });
    }
  }
});

const login1 = (formData) => {
  try {
    axios1
      .post("/login", formData)
      .then((response) => {
        console.log(response);
        // 登录成功后，跳转到首页
        router.push({path:'/'});
      })
      .catch((error) => {
        console.error("登录失败", error);
      });
  } catch (error) {
    console.error("登录失败", error);
  }
};


const login = (formData) => {
  try {
    store.dispatch("auth/login", formData).then((res) => {
      //存储token
      localStorage.setItem("token", res.token);
      console.log('登陆成功'+JSON.stringify(res));
      // 登录成功后，跳转到首页
      //res.user.role
      router.push({path:'/'}); 
    })
  } catch (error) {
    console.error("登录失败", error);
  }
};

// 登录提交函数
const submit = async () => {
  try {
    // 手动触发表单验证
    await LoginFormRef.value.validate();
    // 调用 login 函数进行登录
    await login(LoginForm);
  } catch (error) {
    console.error("登录失败", error);
  }
};
</script>

<style scoped>
/* 这里可以添加登录页面的样式 */
</style>
